<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="震级" prop="hsdSgrade">
                <el-input  v-model="queryParams.hsdSgrade" @input="handleInput" placeholder="请输入震级" clearable type="number" step="any" />
            </el-form-item>
            <el-form-item label="震中烈度" prop="hsdSintensity">
                <el-select v-model="queryParams.hsdSintensity" placeholder="请选择震中烈度" clearable @clear="queryParams.hsdSintensity=undefined">
                    <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="参考地名" prop="hsdReferencename">
                <el-input v-model="queryParams.hsdReferencename" placeholder="请输入参考地名" clearable @clear="queryParams.hsdReferencename=undefined"/>
            </el-form-item>
            <el-form-item label="发震时间">
                <el-form-item  prop="hsdTime" class="hsdTime">
                    <el-date-picker clearable  v-model="queryParams.hsdTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" />
                </el-form-item>
                <span style="display:inline-block;width:30px;text-align:center;color:#606266;">至</span>
                <el-form-item  prop="endTime">
                    <el-date-picker clearable  v-model="queryParams.endTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="上传人" prop="createName">
                <el-input v-model="queryParams.createName" placeholder="请输入上传人" clearable @clear="queryParams.createName=undefined"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAdd">添加</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table ref="tabledRef" v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="hsdId">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true" :selectable="selectable"/>
            <el-table-column label="发震时间（年.月.日）" align="center" prop="textHsdTime" />
            <el-table-column label="震中纬度" align="center" prop="hsdLatitude" />
            <el-table-column label="震中经度" align="center" prop="hsdLongitude" />
            <el-table-column label="震级" align="center" prop="hsdSgrade" />
            <el-table-column label="震源深度（Km）" align="center" prop="hsdSdepth" />
            <el-table-column label="震中烈度" align="center" prop="hsdSintensity" />
            <el-table-column label="精度" align="center" prop="hsdPrecision" />
            <el-table-column label="参考地名" align="center" prop="hsdReferencename" />
            <el-table-column label="上传人" align="center" prop="createName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button type="text" @click="detailDed(scope.row)">查看</el-button>
                    <el-button type="text" @click="handleUpdate(scope.row)" v-if="scope.row.role=='0'">修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 添加弹出框 -->
        <el-dialog :title="title" v-model="open" append-to-body>
            <p class="dialogTitle">{{ title }}</p>
            <el-form ref="historyRiskRef" :model="form" :rules="rules" label-width="150px" style="padding:0 40px 0px 20px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="震级" prop="hsdSgrade">
                            <el-input v-model="form.hsdSgrade" placeholder="请输入震级" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <template v-if="isInput && title=='修改历史地震信息'">
                            <el-form-item label="发震时间" prop="textHsdTime">
                                <el-input v-model="form.textHsdTime" placeholder="请输入发震时间" />
                            </el-form-item>
                        </template>
                        <template v-else>
                            <el-form-item label="发震时间" prop="hsdTime">
                                <el-date-picker v-model="form.hsdTime" type="date" placeholder="YYYY-MM-DD" style="width: 100% !important;"
                                    value-format="YYYY-MM-DD" clearable />
                            </el-form-item>
                        </template>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震中纬度" prop="hsdLatitude">
                            <el-input v-model="form.hsdLatitude" placeholder="请输入震中纬度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震中经度" prop="hsdLongitude">
                            <el-input v-model="form.hsdLongitude" placeholder="请输入震中经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震源深度 (km)" prop="hsdSdepth">
                            <el-input v-model="form.hsdSdepth" placeholder="请输入震源深度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震中烈度" prop="hsdSintensity">
                            <el-select v-model="form.hsdSintensity" placeholder="请选择震中烈度" clearable style="width: 100% !important;">
                                <el-option v-for="item in option" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="精度" prop="hsdPrecision">
                            <el-input v-model="form.hsdPrecision" placeholder="请输入精度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="参考地名" prop="hsdReferencename">
                            <el-input v-model="form.hsdReferencename" placeholder="请输入参考地名" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 查看弹出框 -->
        <el-dialog v-model="openDetail" title="查看历史地震信息" width="900px" append-to-body>
            <p class="dialogTitle">查看历史地震信息</p>
            <HistoryRisk :form="form" />
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
          <p></p>
           <el-upload
              ref="uploadRef"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url"
              :disabled="upload.isUploading"
              :before-upload="handleFileBeforeUpload"
              :on-progress="handleFileUploadProgress"
              :on-error="handleFileUploadError"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
           >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                 <div class="el-upload__tip text-center">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('历史地震信息模板.xlsx')">下载模板</el-link>
                 </div>
              </template>
           </el-upload>
           <template #footer>
              <div class="dialog-footer">
                 <el-button type="primary" @click="submitFileForm">确 定</el-button>
                 <el-button plain @click="upload.open = false">取 消</el-button>
              </div>
           </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="historyRisk">
import { positive2decimals, positive1decimals } from "@/utils/history.js"
import { getAllHistoricalSeismicData, updateHistoricalSeismicData, saveHistoricalSeismicData, delHistoricalSeismicData, getHistoricalSeismicData,getPermission } from "@/api/basedatamanage/historyRisk.js"
import HistoryRisk from "./historyRisk.vue"
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const open = ref(false);
const openDetail = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isEdit = ref(true);
const showSearch = ref(true);
// const permission = ref(true);
const isInput = ref(false);

/*** 导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "token " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/historicalSeismicData/importExcelHistoricalSeismicData"
});
// 最多保留两位小数
const positive2decimal = (rule, value, callback) => {
  value = String(value)
  if (isNaN(value) || !value) {
    callback(new Error());
  } else if (value.indexOf(".") != -1 && (value.split('.').length > 2 || value.split('.')[0] === '' || value.split('.')[1] === '')) {
    callback(new Error()) //防止输入多个小数点
  } else if (value.indexOf(".") != -1 && value.split('.')[1].length > 2) {
    callback(new Error()) //小数点后两位
  } else {
    callback();
  }
}
const dataRules = (rule, value, callback) => {
    if (!value) {
        return callback(new Error());
      }else if (!value.includes('.')) {
        return callback(new Error());
      }else{
        callback();
      }
}
const option = [{ value: 'V', label: 'V' }, { value: 'VI', label: 'VI' }, { value: 'VII', label: 'VII' }, { value: 'VIII', label: 'VIII' }, { value: 'IX', label: 'IX' }, { value: 'X', label: 'X' }];
const data = reactive({
    form: {
        hsdTime: undefined,
        hsdLongitude: undefined,
        hsdLatitude: undefined,
        hsdSgrade: undefined,
        hsdSdepth: undefined,
        hsdSintensity: undefined,
        hsdPrecision: undefined,
        hsdReferencename: undefined,
        textHsdTime:undefined,
    },
    queryParams: {
        page: 1,
        rows: 10,
        hsdSgrade: undefined,
        hsdSintensity: undefined,
        hsdReferencename: undefined,
        hsdTime: undefined,
        endTime:undefined,
    },
    rules: {
        hsdLongitude: [{ required: true, message: "请输入正确的数值，保留两位小数", trigger: 'blur',validator: positive2decimals }],
        hsdLatitude: [{ required: true, message: "请输入正确的数值，保留两位小数", trigger: 'blur',validator: positive2decimals }],
        hsdTime: [{ required: true, message: "请选择发震时间", trigger: 'change' }],
        textHsdTime: [{ required: true, message: "请输入发震时间", trigger: 'blur' ,validator: dataRules}],
        hsdSgrade: [{ required: true, message: '请输入正确的数值，保留两位小数', trigger: 'blur', validator: positive2decimal }],
        hsdSdepth: [{ required: true, message: '震源深度不能为空', trigger: 'blur' }],
        hsdSintensity: [{ required: false, message: "震中烈度不能为空", trigger: "change" }],
        hsdReferencename: [{ required: true, message: '参考地名不能为空', trigger: 'blur' }],
    }
})
const { queryParams, form, rules } = toRefs(data)


watch(queryParams.value, (val) => {
    if (val.hsdTime && val.endTime) {
          const startDate = val.hsdTime
          const endDate = val.endTime
          const startTime = new Date(startDate).getTime()
          const endTime = new Date(endDate).getTime()
          if (startTime > endTime) {
            proxy.$message.error('结束日期必须大于开始日期，请重新选择！')
            val.endTime = ''
          }
        }
})

const handleInput = (value) => {
  // 使用正则表达式限制最多两位小数
  const regex = /^\d*(\.\d{0,2})?$/;
  if (!regex.test(value)) {
    // 如果不符合规则，恢复之前的值
    const previousValue = value.slice(0, -1);
    queryParams.hsdSgrade = previousValue;
  }
};
/** 搜索按钮操作 */
function handleQuery() {
    console.log(queryParams.value)
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    queryParams.value.hsdTime = undefined;
    queryParams.value.endTime = undefined;
//  disabledStart.value = '';
//  disabledEnd.value = '';
    proxy.resetForm("queryRef");
    handleQuery();
}

// 重置表单
function reset() {
    form.value = {
        hsdTime: undefined,
        hsdLongitude: undefined,
        hsdLatitude: undefined,
        hsdSgrade: undefined,
        hsdSdepth: undefined,
        hsdSintensity: undefined,
        hsdPrecision: undefined,
        hsdReferencename: undefined,
        textHsdTime:undefined,
    }
    proxy.resetForm("historyRiskRef");
}

const selectable = row => {
    return row.role == '0'
}
// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.hsdId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 查询历史地震信息列表 */
function getList() {
    loading.value = true;
    if(queryParams.value.time!=undefined){
        queryParams.value.hsdTime = JSON.parse(JSON.stringify(queryParams.value.time))[0]
        queryParams.value.endTime = JSON.parse(JSON.stringify(queryParams.value.time))[1]
    }
    getAllHistoricalSeismicData(queryParams.value).then(response => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    });
}


// 添加
function handleAdd() {
    title.value = "添加历史地震信息"
    open.value = true;
    reset();
}

const tabledRef =ref()
/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除勾选的历史地震信息数据？').then(function () {
        return delHistoricalSeismicData(id);
    }).then((res) => {
        getList();
        proxy.$modal.msgSuccess('删除成功');
        tabledRef.value?.clearSelection();
    }).catch(() => { });
}

// 修改
function handleUpdate(row) {
    reset();
    isEdit.value = true;
    getDetail(row.hsdId)
}
function getDetail(id) {
    getHistoricalSeismicData(id).then(response => {
        form.value = response.data;
        // form.value.hsdTime = response.data.hsdTime
        if (isEdit.value) {
            open.value = true;
            var reg = /^[0-9]*$/;
            console.log(form.value.textHsdTime.split('.').join(''),'日期');
            isInput.value =!reg.test(form.value.textHsdTime.split('.').join(''))
            console.log(isInput.value,'是否为正确日期');
            title.value = "修改历史地震信息"
        } else {
            openDetail.value = true;
        }
    })
}
/** 查看方法*/
function detailDed(row) {
    reset();
    isEdit.value = false;
    openDetail.value = true;
    getDetail(row.hsdId)
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["historyRiskRef"].validate(valid => {
        if (valid) {
            if (title.value == "修改历史地震信息") {
                if(isInput.value){
                    form.value.hsdTime = '';
                }
                updateHistoricalSeismicData(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                saveHistoricalSeismicData(form.value).then(response => {
                    proxy.$modal.msgSuccess("保存成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

// 模板下载
function importTemplate(name) {
  proxy.download("/base/product/downloadExcel", {
    fileName:name
  }, name);
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 导出按钮操作 */
function handleExport() {
    proxy.download('/historicalSeismicData/exportExcelHistoricalSeismicData', {
        ...queryParams.value
    }, `历史地震信息${new Date().getTime()}.xls`)
}

// 获取权限
/* function getPermissionPeo(){
    getPermission().then(res=>{
        permission.value = res.data.message =='是';
    })
} */

// getPermissionPeo();
getList();
</script>
  
<style lang="scss" scoped>
.hsdTime{
    margin-right: 0px!important;

}
</style>